/**
 * Module dependencies
 */
var Room = require('./room');
var consts = require('../../consts/consts');
var utils = require('../../util/utils');

var exp = module.exports;

// global room container(roomId:roomObj)
var gRoomObjDict = {};
var gRoomList = [];
var gRoomNum = 0;
var gRoomId = 0;

// 全局房间管理
/**
 * 用户进入游戏
 * in: msg: {serverId, playerId, token, gameId, playerName, isRobot, ip}
 */
exp.enterGame = function (msg, cb) {

    console.log('roomManager.enterGame caught ----------------');
    //如果没房间，建1个房间
    if (gRoomList.length === 0) {
        // 从new Room() 开始，就已经开始进行room.initGame()，之后就一直在不停地循环状态
        var roomObj = new Room(++gRoomId, msg.gameId, 'room' + gRoomId);
        // gRoomId: 1, gameId: 1, name: room1; roomId = gRoomId;
        // 下面的gRoomObjDict[gRoomId] 不可以用roomObj来替换，因为在已经存在房间的情况下，是不会有roomObj这个变量新建的
        gRoomObjDict[roomObj.roomId] = roomObj;  // 把roomObj存起来
        gRoomList.push(roomObj.roomId);
        gRoomNum++;
    }

    // 暂时只需要一个房间
    // 其实就是roomObj.addPlayer(msg)和roomObj.getGameStatus();
    gRoomObjDict[gRoomId].addPlayer(msg, function (err) {
        if (!err) {
            //cb回调会返回数据给客户端，这里需要返回当前游戏状态
            var gameData = gRoomObjDict[gRoomId].getGameStatus();
            var playerData = gRoomObjDict[gRoomId].getPlayerData(msg.playerId);
            var playerList = gRoomObjDict[gRoomId].getPlayerList();
            var banker = gRoomObjDict[gRoomId].getCurBankerData();
            var bankerList = gRoomObjDict[gRoomId].getBankerList();

            // 房间设置
            var roomSet = { bankerMinCoin: 500000, sysBankerCoin: 1000000000 };

            if (gameData.gameStatus === 3) {
                gameData.cards = gRoomObjDict[gRoomId].curCards;
            }

            var ret = {
                gameId: msg.gameId,
                roomId: gRoomId,
                gameData: gameData,
                playerData: playerData,
                playerList: playerList,
                bankerData: banker,
                bankerList: bankerList,
                roomSet: roomSet
            };

            utils.invokeCallback(cb, null, ret);
        } else {
            console.log(err);
            utils.invokeCallback(cb, err, null);
        }
    });
};

// 申请上庄
exp.applyBanker = function (msg, cb) {
    var roomId = msg.roomId;
    gRoomObjDict[roomId].applyBanker(msg, cb);
};

// 申请下庄
exp.cancelBanker = function (msg, cb) {
    var roomId = msg.roomId;
    gRoomObjDict[roomId].cancelBanker(msg, cb);
};

// 申请插队上庄
exp.cutInBanker = function (msg, cb) {
    var roomId = msg.roomId;
    gRoomObjDict[roomId].cutInBanker(msg, cb);
};

// 申请下注
exp.bid = function (roomId, playerId, msg) {
    var ret = gRoomObjDict[roomId].bid(playerId, msg);
    return ret;
};

exp.getRoomById = function (roomId) {
    var roomObj = gRoomObjDict[roomId];
    return roomObj || null;
};

exp.kick = function (msg) {
    var room = this.getRoomById(msg.roomId);
    room.kickPlayer(msg);
};
